package com.netmera.mobile;

import v2.simpleUi.M_Caption;
import v2.simpleUi.M_Container;
import v2.simpleUi.M_EmailInput;
import v3.M_TextModifier;
import android.app.Activity;
import android.content.Context;
import android.view.View;
import android.widget.Toast;

public abstract class M_LoginForm extends M_Container {
	private String email;
	protected String password;

	public M_LoginForm() {

		add(new M_Caption("User Login"));

		add(new M_EmailInput() {

			@Override
			public boolean save(String validEmailAddress) {
				email = validEmailAddress;
				return true;
			}

			@Override
			public String load() {
				return "";
			}

			@Override
			public String getVarName() {
				return "Email";
			}
		});

		M_TextModifier pw = new M_TextModifier() {

			private Activity myContext;

			@Override
			public boolean save(String newValue) {
				if (newValue.length() < 4) {
					return false;
				}
				password = newValue;
				loginUser(myContext);
				return false;
			}

			@Override
			public View getView(Context context) {
				myContext = (Activity) context;
				return super.getView(context);
			}

			@Override
			public String load() {
				return "";
			}

			@Override
			public String getVarName() {
				return "Password";
			}
		};
		pw.isPasswordInput(true);
		add(pw);
	}

	protected void loginUser(final Activity a) {
		NetmeraUser.loginInBackground(email, password,
				new NetmeraCallback<NetmeraUser>() {
					@Override
					public void callback(NetmeraUser result,
							NetmeraException exception) {
						if (result != null && exception == null) {
							// Success
							onUserLoggedIn(result, password);
							a.finish();
						} else {
							// Error occurred
							exception.printStackTrace();
							toast(a, "User could not be logged in");
						}
					}
				});
	}

	private void toast(Context a, String string) {
		Toast.makeText(a, string, Toast.LENGTH_LONG).show();
	}

	public abstract void onUserLoggedIn(NetmeraUser u, String pw);
}
